package com.legal.app.service;

import com.legal.app.config.WechatOpenConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class WechatService {
    @Autowired
    private WechatOpenConfig config;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取微信授权URL
     */
    public String getAuthorizationUrl(String state) {
        return String.format(
                "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                config.getAppId(),
                config.getRedirectUri(),
                config.getScope(),
                state
        );
    }

    /**
     * 通过code获取AccessToken
     */
    public Map<String, Object> getAccessToken(String code) {
        String url = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                        "appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                config.getAppId(),
                config.getAppSecret(),
                code
        );

        ResponseEntity<Map> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                Map.class
        );

        return response.getBody();
    }

    /**
     * 获取用户信息
     */
    public Map<String, Object> getUserInfo(String accessToken, String openId) {
        String url = String.format(
                "https://api.weixin.qq.com/sns/userinfo?" +
                        "access_token=%s&openid=%s&lang=zh_CN",
                accessToken,
                openId
        );

        ResponseEntity<Map> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                Map.class
        );

        return response.getBody();
    }
}